package cn.school.handler;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
//埋点
public class TimingInterceptor extends HandlerInterceptorAdapter {
    //返回false,不执行controller(mapping)
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //request.setCharacterEncoding("utf-8");
        System.out.println("请求:"+request.getServletPath()+" 开始于:"+new Date()+",拦截了:"+handler);
        request.setAttribute("start",System.nanoTime());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //super.postHandle(request, response, handler, modelAndView);
        System.out.println("请求:"+request.getServletPath()+" 结束于:"+new Date()+",拦截了:"+handler);
        if(modelAndView!=null){
            System.out.println("视图是:"+modelAndView.getViewName()+",返回值:"+modelAndView);
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //super.afterCompletion(request, response, handler, ex);
        long end=System.nanoTime();
        long start=(Long)request.getAttribute("start");
        System.out.println("请求:"+request.getServletPath()+"耗时:"+(end-start)+"纳秒");
    }
}
